package com.yonggle.springbootdemo.generate;

import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.util.ArrayList;

public class XmlUtil {

    public static String toXml(Object object) {
        JAXBContext jaxbContext = getJaxbContext(object.getClass());
        try {
            Writer w = new StringWriter();
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(object, w);
            return w.toString();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static <T> T toObject(String xml, Class<T> clazz) {
        JAXBContext jaxbContext = getJaxbContext(clazz);
        try {
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            Reader reader = new StringReader(xml);
            JAXBElement<T> unmarshal = unmarshaller.unmarshal(new StreamSource(reader), clazz);
            return unmarshal.getValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T toObject(InputStream in, Class<T> clazz) {
        JAXBContext jaxbContext = getJaxbContext(clazz);
        try {
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            JAXBElement<T> unmarshal = unmarshaller.unmarshal(new StreamSource(in), clazz);
            return unmarshal.getValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private static JAXBContext getJaxbContext(Class clazz) {
        JAXBContext jaxbContext = null;
        if (jaxbContext == null) {
            try {
                jaxbContext = JAXBContext.newInstance(clazz, ArrayList.class);
            } catch (JAXBException ex) {
                throw new RuntimeException("Could not instantiate JAXBContext for class [" + clazz + "]: "
                        + ex.getMessage(), ex);
            }
        }
        return jaxbContext;
    }


}
